import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { Image, Modal, message } from "antd";
import styles from "./BooksDetail.module.css";
import PageHeader from "../PageHeader";
import { getBookDetailById } from "@/api/book";
import { editUser } from "@/api/user";
import Discuss from "../Discuss";
import { useSelector, useDispatch } from "react-redux";
import { updateUserInfoAsync } from "@/redux/userSlice";
export default function BooksDetail() {
  const { id } = useParams();
  const bookId = id?.toString()?.split("=")[1];
  const [bookInfo, setBookInfo] = useState(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const dispatch = useDispatch();
  const { isLogin, userInfo } = useSelector((state) => state.user);
  const showModal = () => {
    setIsModalOpen(true);
  };
  const handleOk = () => {
    // 确定下载 -> 判断积分是否足够
    if (userInfo.points - bookInfo?.requirePoints < 0) {
      message.warning("积分不足，少侠请赚足积分在来~");
    } else {
      // 积分是够的 -> 扣除积分
      editUser(userInfo?._id, {
        points: userInfo.points - bookInfo?.requirePoints,
      });
      // 本地仓库也需要更新
      dispatch(
        updateUserInfoAsync({
          userId: userInfo._id,
          newInfo: { points: userInfo.points - bookInfo?.requirePoints },
        })
      );
      window.open(`${bookInfo?.downloadLink}`);
    }
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  useEffect(() => {
    async function fetchData() {
      const { data } = await getBookDetailById(bookId);
      setBookInfo(data);
    }
    fetchData();
  }, [bookId]);

  return (
    <>
      <PageHeader title={"书籍详情"} />
      <div className={styles.booksDetailContainer}>
        {/* 左边 */}
        <div className={styles.leftSide}>
          <Image width={240} height={320} src={bookInfo?.bookPic} />
          <div className={styles.content}>
            <span>
              下载所需积分：
              <i>{bookInfo?.requirePoints}</i>分
            </span>
            {isLogin ? (
              <span className={styles.downloadLink} onClick={showModal}>
                百度云下载地址
              </span>
            ) : null}
            <span>在线预览</span>
          </div>
        </div>
        {/* 右边 */}
        <div className={styles.rightSide}>
          <div className={styles.title}>{bookInfo?.bookTitle}</div>
          <div dangerouslySetInnerHTML={{ __html: bookInfo?.bookIntro }}></div>
        </div>
      </div>
      <div style={{ margin: "10px 40px" }}>
        <Discuss commentType={2} targetId={bookInfo?._id} bookInfo={bookInfo} />
      </div>
      <Modal title="重要提示" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        是否确定要花费{bookInfo?.requirePoints}分，下载这本书？
      </Modal>
    </>
  );
}
